window.addEventListener('DOMContentLoaded', () => {
  app.initPage();
});

function loadPage() {
  setTimeout(() => {
    isTeaLogin();
  }, 200);
  loadClazzForm();
  $.get(`${app.urlLocation.queryAllCt}/${app.pageHelper.global_page}/${app.pageHelper.global_limit}`, res => {
    if (res.data.length === 0 && app.pageHelper.global_page > 1) {
      app.pageHelper.global_page--;
      loadPage();
    } else {
      loadClazzTable(res);
      loadClazzPage(res);
    }
  })
}

function loadClazzTable(clazz) {
  layui.use(['table', 'layer'], () => {
    let table = layui.table,
        layer = layui.layer;
    table.render({
      elem: '#clazz',
      data: clazz.data,
      limit: app.pageHelper.global_limit,
      cols: [
        [
          {field: 'id', title: '科目编号', width: 295},
          {field: 'classType', title: '科目名称'},
          {field: 'createdTime', title: '科目创建时间'},
          {title: '操作', toolbar: '#clazz-tool'}
        ]
      ]
    });
    table.on('tool(clazz)', obj => {
      let event = obj.event,
          data = obj.data;
      if (event === 'del') {
        layer.confirm('删除将不可恢复，是否删除?', {
          btn: ['删除', '不删除']
        }, () => {
          $.get(`${app.urlLocation.queryTeacherByCondition}`, {clazz: data.id}, teacher => {
            if (teacher.length === 0) {
              $.post(`${app.urlLocation.deleteCt}`, {id: data.id}, res => {
                if (res === 200)
                  layer.msg('科目信息删除成功');
                else
                  layer.msg('科目信息删除失败，请重试或联系系统管理员');
                loadPage();
              });
            } else {
              layer.msg('科目已关联教师，无法删除');
            }
          })
        })
      }
    });
  })
}

function loadClazzPage(clazz) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'clazz-page',
      curr: app.pageHelper.global_page,
      count: clazz.count,
      limit: app.pageHelper.global_limit,
      limits: [10, 20, 30, 40, 50],
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          app.pageHelper.global_page = obj.curr;
          app.pageHelper.global_limit = obj.limit;
          loadPage();
        }
      }
    });
  })
}

function loadClazzForm() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
        layer = layui.layer;
    form.on('submit(add)', obj => {
      let field = obj.field;
      $.get(`${app.urlLocation.queryCtByName}`, field, ct => {
        if (ct === '') {
          $.post(`${app.urlLocation.addCt}`, field, res => {
            if (res === 200) {
              layer.msg('科目信息添加成功');
              $('.menu-box form')[0].reset();
            } else {
              layer.msg('科目信息添加失败');
            }
            loadPage();
          });
        } else {
          $('.body-box form')[0].reset();
          layer.msg('该科目已存在，请勿重复添加');
        }
      })
    })
  })
}